package com.googlecodes.tfhwiz.resourceutil.impl;

import java.io.IOException;

import com.googlecodes.tfhwiz.resourceutil.ResourceManager;

/**
 * Resource loading manager with caching .
 * simple implement
 *
 */
public class CachingResourceManager<R> extends ResourceManager<R> {
    public static final long NO_INTERVAL = -1L;
    private long interval = 1000L*60*10; // 10 minutes
    private long loadTime = 0L;
    private Object lock = new Object();

    private R resource;


    /**
     *
     */
    public long getInterval() {return interval;}
    /**
     * interval loading resouce.
     * if it is NO_INTERVAL(-1), interval is nothing
     */
    public void setInterval(long interval) {this.interval = interval;}

    /**
     *
     */
    public long getLoadTime() {return loadTime;}

    /**
     * return resource
     * if isn't possible return null.
     *
     */
    @Override
    public R getResource() {
        synchronized(lock) {
            if (resource == null || checkModified()) {
                getActualResource();
            }
        }
        return resource;
    }

    protected boolean checkModified() {
        if (interval != NO_INTERVAL) {
            if ((getLoadTime() + getInterval()) > System.currentTimeMillis()) {
                return false;
            }
        }
        if (interval == NO_INTERVAL ||
                (getLoadTime() + getInterval()) < System.currentTimeMillis()) {
            if (getLoadTime() < getResourceLoader().getTimestamp()) {
                return true;
            }
        }
        return false;
    }

    protected void getActualResource() {
        resource = super.getResource();
        loadTime = System.currentTimeMillis();
    }
}

